package sketch.util;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * A class keeping track of all generated intermediate files during test creation.
 * The major intermediate files include:
 * 1. instrumentation files
 * 2. drivers for symbolic execution
 * 3. the trace file to keep recorded values
 * 4. files after expansion (be aware of this kind)
 * */
public class IntermediateFiles {
	
	private static Set<String> generated_intermediate_file_path = new HashSet<String>();
	
	public static void addIntermediateFile(File f) {
		Checker.checkNull(f, "The file added should not be null.");
		addIntermediateFile(f.getAbsolutePath());
	}
	
	public static void addIntermediateFile(String filePath) {
		generated_intermediate_file_path.add(filePath);
	}
	
	public static void retainIntermediateFile(String filePath) {
		generated_intermediate_file_path.remove(filePath);
	}
	
	public static void addAllFilesAsIntermediates(String dir, String suffix) {
		List<File> allfiles = FileListing.getFiles(new File(dir));
		for(File f : allfiles) {
			if(suffix == null) {
				addIntermediateFile(f);
			} else {
				if(f.getAbsolutePath().endsWith(suffix)) {
					addIntermediateFile(f);
				}
			}
		}
	}
	
	public static void addAllFilesAsIntermediatesNoRecursive(String dir, String suffix) {
		File dirfile = new File(dir);
		if(!dirfile.isDirectory()) {
			return;
		}
		File[] files = dirfile.listFiles();
		for(File f : files) {
			if(suffix == null) {
				addIntermediateFile(f);
			} else {
				if(f.getAbsolutePath().endsWith(suffix)) {
					addIntermediateFile(f);
				}
			}
		}
	}
	
	public static void retainIntermediateFile(File f) {
		retainIntermediateFile(f.getAbsolutePath());
	}
	
	public static void deleteIntermediateFiles() {
	    SketchUtil.stdln("Deleting all intermediate files: ");
	    int count = 0;
		for(String file_path : generated_intermediate_file_path) {
			SketchUtil.stdln("  deleting: " + file_path);
			boolean r = SketchUtil.delete_file(file_path);
			count = r ? count + 1 : count;
		}
		SketchUtil.stdln(count + " files deleted.");
		//clear the set
		generated_intermediate_file_path.clear();
	}
}